package alg20241221;

public class Text {
    int[] tmp;
    public int reversePairs(int[] record) {
        int n = record.length;
        tmp = new int[n];
        return marge(record, 0, n - 1);
    }

    public int marge(int[] nums, int left, int right){
        if(left >= right) return 0;
        int mid = (left + right) / 2;
        int ret = 0;

        ret += marge(nums, left , mid);
        ret += marge(nums, mid + 1, right);
        int cur1 = left, cur2 = mid + 1, i = 0;
        while(cur1 <= mid && cur2 <= right){
            while(cur1 <= mid && nums[cur1] <= nums[cur2])
                tmp[i++] = nums[cur1++];
            while(cur2 <= right && nums[cur2] < nums[cur1]) {
                tmp[i++] = nums[cur2++];
                ret += mid - cur1 + 1;
            }
        }
        while(cur1 <= mid) {
            tmp[i++] = nums[cur1++];
        }
        while(cur2 <= right) tmp[i++] = nums[cur2++];

        for (int j = left; j <= right; j++) {
            nums[j] = tmp[j - left];
        }
        return ret;


    }
}
